import { onMounted, ref } from 'vue';
import { getDisease } from './geoJson';
import { getWeather } from './getWeather';
// 封装加载相应区域代码的geojson数据
export const addMap = () => {
    const covid = ref(null)
    const covidCity = ref(null)
    const weatherCity = ref(null)
    const map = ref(null);
    const source = ref(null)
    const style = new ol.style.Style({
        fill: new ol.style.Fill({
            color: "rgba(0, 0, 0, 0.3)"
        }),
        stroke: new ol.style.Stroke({
            color: "#999",
            width: 2
        })
    })
    const layer = new ol.layer.Vector({
        style,
    })
    /* 生成标注 */
    const getPop = async (code, lng, lat) => {
        /* 获取天气 */
        weatherCity.value = await getWeather(code)
        /* 获取疫情数据 */
        covid.value = await getDisease()

        console.log(covid.value);
        let city = weatherCity.value.city
        city = city.substr(0, city.length - 1)
        if (
            city == "北京" || city == "上海" || city == "天津" || city == "重庆"
        ) {
            covidCity.value = covid.value.find(item => {
                item.name == city
            })
        } else {
            covid.value.forEach(item => {
              let  findCovid =  item.city.find((i) =>i.name == city)
                if (findCovid) {
                    covidCity.value = findCovid
                }
            })
            
        }
        var iconFeature = new ol.Feature({
            geometry: new ol.geom.Point([lng, lat])
        });
        /* 2、设置标注的样式信息 */
        const iconStyle = new ol.style.Style({
            /**{olx.style.IconOptions}类型*/
            text: new ol.style.Text({
                //位置
                textAlign: 'center',
                //基准线
                textBaseline: 'middle',
                //文字样式
                font: 'normal 14px 微软雅黑',
                //文本内容
                text: city,
                //文本填充样式（即文字颜色）
                fill: new ol.style.Fill({ color: '#aa3300' }),
                stroke: new ol.style.Stroke({ color: '#ffcc33', width: 2 })
            }),
            image: new ol.style.Icon(
                ({
                    anchor: [0.5, 60],
                    anchorOrigin: 'top-right',
                    anchorXUnits: 'fraction',
                    anchorYUnits: 'pixels',
                    offsetOrigin: 'top-right',
                    offset: [0, -50],
                    //图标缩放比例
                    scale: 0.15,
                    //透明度
                    opacity: 0.75,
                    //图标的url
                    src: '/src/assets/location.png'
                })
            )
        });
        iconFeature.setStyle(iconStyle);
        /* 3、将标注添加到矢量数据源中 */
        //矢量标注的数据源
        var vectorSource = new ol.source.Vector({
            features: [iconFeature]
        });
        /* 4、将数据源添加到矢量图层中 */
        var vectorLayer = new ol.layer.Vector({
            source: vectorSource
        });
        /* 5、将矢量图层添加到Map容器上 */
        map.value.addLayer(vectorLayer);
        /* 3、创建Overlay */
        /**
        * 实现popup的html元素
        */
        var container = document.getElementById('popup');
        var content = document.getElementById('popup-content');
        var closer = document.getElementById('popup-closer');
        //新增img元素
        //示例标注点北京市的信息对象
        var featuerInfo = {
            geo: [lng, lat],
            att: {
                //标注信息的标题内容
                title: city,
                //标注详细信息链接
                titleURL: "http://www.openlayers.org/",
                //标注内容简介
                text: weatherCity.value.weather,
                //标注的图片
                imgURL: "/src/assets/bg.png"
            }
        }
        /**
     * 动态设置元素文本内容（兼容）
     */
        function setInnerText(element, text) {
            if (typeof element.textContent == "string") {
                element.textContent = text;
            } else {
                element.innerText = text;
            }
        }
        function addFeatrueInfo(info) {
            //新增a元素
            var elementA = document.createElement('a');
            elementA.className = "markerInfo";
            elementA.href = info.att.titleURL;
            //elementA.innerText = info.att.title;
            setInnerText(elementA, info.att.title);
            // 新建的div元素添加a子节点
            content.appendChild(elementA);
            //新增div元素
            var elementDiv = document.createElement('div');
            elementDiv.className = "markerText";
            //elementDiv.innerText = info.att.text;
            setInnerText(elementDiv, info.att.text);
            // 为content添加div子节点
            content.appendChild(elementDiv);
            //新增img元素
            var elementSpan = document.createElement('span');
            console.log(covidCity.value);
            setInnerText(elementSpan, `现有确诊${covidCity.value.conNum}`);
            // 为content添加img子节点
            content.appendChild(elementSpan);
        }
        /**
        * 在地图容器中创建一个Overlay
        */
        var popup = new ol.Overlay(
            /** @type {olx.OverlayOptions} */
            ({
                //要转换成overlay的HTML元素
                element: container,
                //当前窗口可见
                autoPan: true,
                //Popup放置的位置
                positioning: 'bottom-center',
                //是否应该停止事件传播到地图窗口
                stopEvent: false,
                autoPanAnimation: {
                    //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度
                    duration: 500
                }
            }));
        map.value.addOverlay(popup);
        /* 4、事件监听 */
        closer.onclick = function () {
            //未定义popup位置
            popup.setPosition(undefined);
            //失去焦点
            closer.blur();
            return false;
        };
        /**
              * 为map添加点击事件监听，渲染弹出popup
              */
        map.value.on('click', function (evt) {
            //判断当前单击处是否有要素，捕获到要素时弹出popup
            var feature = map.value.forEachFeatureAtPixel(evt.pixel, function (feature, vectorLayer) { return feature; });
            if (feature) {
                //清空popup的内容容器
                content.innerHTML = '';
                //在popup中加载当前要素的具体信息
                addFeatrueInfo(featuerInfo);
                if (popup.getPosition() == undefined) {
                    var position = feature.getGeometry().flatCoordinates
                    popup.setPosition(position)
                }
            }
        });
        /**
        * 为map添加鼠标移动事件监听，当指向标注时改变鼠标光标状态
        */
        map.value.on('pointermove', function (e) {
            var pixel = map.value.getEventPixel(e.originalEvent);
            var hit = map.value.hasFeatureAtPixel(pixel);
            map.value.getTargetElement().style.cursor = hit ? 'pointer' : '';
        });
    }
    /* ------------------------------ */
    const loadGeoJsonFly = (code, lng, lat) => {
        /* 加载弹窗标注 */
        getPop(code, lng, lat)

        if (source.value) {
            source.value.clear()
        }
        const url = `https://geo.datav.aliyun.com/areas_v3/bound/${code}.json`;
        source.value = new ol.source.Vector({
            url: url,
            format: new ol.format.GeoJSON()//解析geojson数据
        })
        layer.setSource(source.value)
        setTimeout(() => {
            let view = map.value.getView();
            view.animate({
                center: [lng, lat],
                zoom: 8,
                duration: 2000
            })
        });
    }
    const initMap = (code, lng, lat) => {
        /* 高德地图 */
        const gaode = new ol.layer.Tile({
            title: "高德地图",
            source: new ol.source.XYZ({
                url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
                wrapX: false,
                crossOrigin: "Anonymous"
            })
        });
        map.value = new ol.Map({
            target: 'map',
            layers: [gaode],
            view: new ol.View({
                projection: 'EPSG:4326',
                center: [lng, lat],
                zoom: 4
            })
        })
        map.value.addLayer(layer)
        loadGeoJsonFly(code, lng, lat)



    }
    return { initMap, loadGeoJsonFly }
}

